package ZengJiHong2.Test6;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @ClassName myLinkedList
 * @Author 16799
 * @Date 2025/8/20 17:40
 * @Version 1.0
 * @Description TODO
 **/
public class myLinkedList<E> {
    private int size;

    //linkedList的addLast源码里面也是这样类似写的，定义的是静态内部类
    //Node泛型类，用于代表链表的结点。每个结点包含（数据data，和下一个结点的地址值next）
    public static class Node<E>{
        E data;
        Node<E> next;

        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }
    }

    //add方法，返回头结点
    public Node<E> add(){
        Node<E> head = null;
        Scanner sc = new Scanner(System.in);

        while (true){
            System.out.println("请输入要添加的链表结点值");
            String data = sc.next();
            if (data.equals("exit")){
                break;
            }
            if (head == null){
                //初始化
                head = new Node(data,null);
                size++;
            }else {
                //尾插法
                Node<E> temp = head;
                //死循环，让指正走到最后一个结点
                while (temp.next!=null){
                    temp = temp.next;
                }

                temp.next = new Node(data,null);
                size++;
            }
        }
        return head;
    }


    public Node<E> reverse(Node<E> head,int left,int right){
        if (head == null||left<1||left>size||right<1||right>size
            ||left==right||left>right){
            return head;
        }

        Node<E> first = head;
        Node<E> mark = null;
        //存储需要反转的节点
        List<E> data = new ArrayList<>();
        int index = 0;
        while (head!=null){
            index++;
            if (index == left){
                //head不断指向下一个节点，找到左节点记录下来
                mark = head;
            }

            if (index>=left&&index<=right){
                data.add(head.data);
            }

            if (index==right){
                break;
            }
            head=head.next;
        }

        //倒序遍历
        for (int i = data.size()-1;i>=0 ; i--){
            E e = data.get(i);
            mark.data = e;
            mark = mark.next;
        }

        return first;
    }

    public void foreach(Node<E> head){
        if (head==null){
            System.out.println(head);
            return;
        }

        while (head!=null){
            System.out.print(head.data+" ");
            head = head.next;
        }
    }


}
